using System;
using System.IO;
using System.Text;
using System.Collections;

namespace VCDepend.Engine.Graphviz
{
	public class DotGraph : IDotSerializable
	{
		public readonly string Name;
		
		private DotAttributes m_attributes;
		private ArrayList m_children;

		public DotGraph(string name)
		{
			const string AttributeSeparator = ";\r\n";

			this.Name = name;

			m_attributes = new DotAttributes("", AttributeSeparator, AttributeSeparator);
			m_children = new ArrayList();
		}

		public void SetAttribute(string name, string value)
		{
			m_attributes.SetAttribute(name, value);
		}

		public DotNode AddNode(string name)
		{
			DotNode node = new DotNode(name);
			m_children.Add(node);

			return node;
		}

		public DotEdge AddEdge(string from, string to)
		{
			DotEdge edge = new DotEdge(from, to);
			m_children.Add(edge);

			return edge;
		}

		public void Serialize(TextWriter writer)
		{
			SerializeOpenDigraph(writer);
				SerializeAttributes(writer);
				SerializeChildren(writer);
			SerializeCloseDigraph(writer);
		}

		private void SerializeOpenDigraph(TextWriter writer)
		{
			writer.WriteLine("digraph {0}", DotUtil.EscapeDotString(this.Name));
			writer.WriteLine("{");
		}

		private void SerializeCloseDigraph(TextWriter writer)
		{
			writer.WriteLine("}");
		}

		private void SerializeAttributes(TextWriter writer)
		{
			m_attributes.Serialize(writer);
		}

		private void SerializeChildren(TextWriter writer)
		{
			foreach (IDotSerializable child in m_children)
			{
				child.Serialize(writer);
				writer.Write(Environment.NewLine);
			}
		}
	}
}
